﻿#include <QEventLoop>
#include "MainWindow.h"
#include "qtimer.h"
#include "qpushbutton.h"
#include "./ui_MainWindow.h"
#include "src/utils/utils.h"
#include "libdaq/device/base_device.h"
#include "src/connect_page/connect_page.h"
#include <QComboBox>
#include <QCheckBox>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>

using namespace libdaq::device;

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
	ui->setupUi(this);
	qRegisterMetaType<std::vector<std::vector<float>>>("std::vector<std::vector<float>>");
	// 创建设备
	base_device_ = NewDevice();
	connect(ui->Connnectbutton, &QPushButton::clicked, this, &MainWindow::ClickConnectAction);
	connect(ui->StartADCCollection, &QPushButton::clicked, this, &MainWindow::ClickStartADCCollectionAction);
	connect(ui->UpdateConfig, &QPushButton::clicked, this, &MainWindow::ClickUpdateConfig);
	connect(ui->OnceCollection, &QPushButton::clicked, this, &MainWindow::ClickSoftwareTrigger);
	connect(ui->StopADCCollection, &QPushButton::clicked, this, &MainWindow::ClickStopADCCollection);

	InitWaveWidget();
	InitSampleRateComboBox();
	InitChannelConfiguration();
}

MainWindow::~MainWindow()
{
	EndOnceCollection();
	EndScrollCollection();
	delete ui;
}

void MainWindow::ConnectStatusSlot(bool status, ConnectPage::ConnectType type)
{
	if (status)
	{
		connected_count++;
		if (!base_device_->InitializeDevice())
		{
			qWarning(u8"初始化设备失败，请检查配置参数是否存在错误");
			return;
		}
		if (!base_device_->ConnectedDevice())
		{
			qWarning(u8"发送连接设备命令失败");
			return;
		}
	}
	else
	{
		base_device_->DisconnectedDevice();
	}
}

void MainWindow::ClickConnectAction()
{
	ConnectPage connect_page(base_device_, nullptr);
	// 初始化连接界面
	if (connect_page_.isNull())
	{
		connect_page_.reset(new ConnectPage(base_device_));
		connect_page_->setModal(false);
		connect(connect_page_.get(), &ConnectPage::ConnectStatus, this, &MainWindow::ConnectStatusSlot);
	}
	connect_page_->InitParams(base_device_);
	connect_page_->raise();
	connect_page_->activateWindow();
	connect_page_->show();
}

void MainWindow::ClickStartADCCollectionAction()
{
	if (connected_count == 0)
	{
		qWarning(u8"请先连接设备");
		return;
	}

	if (!is_start_adc_collection_)
	{
		// 开始采集
		is_start_adc_collection_ = true;

		// 清空波形
		base_wave_widget_->Clear();

		// 根据触发模式选择采集方式
		if (IsScrollMode())
		{
			ScrollCollection();
			qInfo(u8"启动滚动模式采集成功");
		}
		else
		{
			OnceCollection();
			qInfo(u8"启动单次触发采集成功");
		}

		base_wave_widget_->replot(QCustomPlot::rpQueuedReplot);
	}
	else
	{
		// 停止采集
		is_start_adc_collection_ = false;
		
		if (IsScrollMode())
		{
			EndScrollCollection();
		}
		else
		{
			EndOnceCollection();
		}
		
		qInfo(u8"停止ADC采集");
	}
}

void MainWindow::OnceCollection()
{
	if (!is_start_adc_collection_)
	{
		return;
	}

	if (!base_device_->StopADCCollection())
	{
		qWarning(u8"停止ADC采集失败");
		is_start_adc_collection_ = false;
		return;
	}

	EndOnceCollection();

	// 延时50ms
	QEventLoop loop;
	QTimer::singleShot(50, &loop, SLOT(quit()));
	loop.exec();

	if (!base_device_->StartADCCollection())
	{
		qWarning(u8"启动ADC采集失败");
		is_start_adc_collection_ = false;
		return;
	}

	// 初始化数据缓冲区
	auto channel_count = base_device_->GetADCLegalChannelSize();
	adc_data_buffer_.resize(channel_count);
	for (auto &buffer : adc_data_buffer_)
	{
		buffer.clear();
	}

	// 获取启用的通道
	QVector<bool> channel_state = GetChannelEnabled();

	// 重置已完成线程计数
	completed_thread_count_ = 0;

	// 为每个启用的通道创建线程
	for (int i = 0; i < channel_state.size(); i++)
	{
		if (!channel_state.at(i))
		{
			continue;
		}

		auto thread = QSharedPointer<OnceTriggerADCThread>::create(base_device_, i, adc_data_buffer_[i]);
		connect(thread.get(), &OnceTriggerADCThread::complete, this, &MainWindow::UpdatePlotData);
		once_trigger_adc_thread_list_.push_back(thread);
		thread->start();
	}
}

void MainWindow::EndOnceCollection()
{
	for (int i = 0; i < once_trigger_adc_thread_list_.size(); i++)
	{
		auto &thread = once_trigger_adc_thread_list_[i];
		if (thread != nullptr)
		{
			thread->quit();
			thread->wait();
			thread = nullptr;
		}
	}
	once_trigger_adc_thread_list_.clear();
}

QVector<bool> MainWindow::GetChannelEnabled()
{
	std::vector<bool> channel_state = base_device_->GetChannelEnableList();
	QVector<bool> channel_state_vector;
	for (auto state : channel_state)
	{
		channel_state_vector.push_back(state);
	}
	return channel_state_vector;
}

bool MainWindow::ConfigADCSampleRate()
{
	// 从UI控件获取选中的采样率
	int selected_index = ui->sampleRateComboBox->currentData().toInt();
	auto legal_sample_rates = base_device_->GetADCLegalSampleRate();

	if (selected_index < 0 || selected_index >= static_cast<int>(legal_sample_rates.size()))
	{
		qWarning(u8"采样率索引超出范围");
		return false;
	}

	auto selected_sample_rate = legal_sample_rates[selected_index];
	if (!base_device_->ConfigADCSampleRate(selected_sample_rate))
	{
		qWarning(u8"采样率配置失败");
		return false;
	}

	qInfo(u8"采样率配置成功: %s", ui->sampleRateComboBox->currentText().toUtf8().constData());
	return true;
}

bool MainWindow::ConfigADCChannel()
{
	// 根据设备通道数动态配置通道使能
	int channel_count = base_device_->GetADCLegalChannelSize();
	uint8_t channel_mask = 0;

	// 根据通道数设置对应的通道使能掩码
	for (int i = 0; i < channel_count; ++i)
	{
		channel_mask |= (1 << i);
	}

	if (!base_device_->ConfigADCChannel(channel_mask))
	{
		qWarning(u8"ADC通道配置失败");
		return false;
	}

	qInfo(u8"ADC通道配置成功，使能通道掩码: 0x%02X", channel_mask);
	return true;
}

bool MainWindow::ConfigADCTrigger()
{
	// 从UI控件获取触发配置参数

	// 触发模式 (ui->triggerModeComboBox)
	LockzhinerADCTriggerType trigger_type;
	int trigger_mode_index = ui->triggerModeComboBox->currentIndex();
	switch (trigger_mode_index)
	{
	case 0: // 滚动模式
		trigger_type = LockzhinerADCTriggerType::Normal;
		break;
	case 1: // 上升沿触发
		trigger_type = LockzhinerADCTriggerType::RisingEdge;
		break;
	case 2: // 下降沿触发
		trigger_type = LockzhinerADCTriggerType::FallingEdge;
		break;
	case 3: // 双边沿触发
		trigger_type = LockzhinerADCTriggerType::DoubleEdge;
		break;
	default:
		trigger_type = LockzhinerADCTriggerType::Normal;
		break;
	}

	// 触发类型 (ui->triggerTypeComboBox)
	LockzhinerADCTriggerMode trigger_mode;
	int trigger_type_index = ui->triggerTypeComboBox->currentIndex();
	switch (trigger_type_index)
	{
	case 0: // 自动触发
		trigger_mode = LockzhinerADCTriggerMode::Automatic;
		break;
	case 1: // 普通触发
		trigger_mode = LockzhinerADCTriggerMode::Common;
		break;
	case 2: // 单次触发
		trigger_mode = LockzhinerADCTriggerMode::Single;
		break;
	default:
		trigger_mode = LockzhinerADCTriggerMode::Single;
		break;
	}

	// 触发通道 (ui->triggerChannelComboBox)
	LockzhinerADCChannel trigger_channel;
	int trigger_channel_index = ui->triggerChannelComboBox->currentIndex();
	if (trigger_channel_index == 0)
	{
		trigger_channel = LockzhinerADCChannel::ADCChannelAINNone; // 软件触发
	}
	else
	{
		// 根据通道索引设置对应的通道
		trigger_channel = static_cast<LockzhinerADCChannel>(1 << (trigger_channel_index - 1));
	}

	// 触发电平 (ui->triggerLevelSpinBox)
	int trigger_level = ui->triggerLevelSpinBox->value();

	if (!base_device_->ConfigADCTrigger(trigger_type, trigger_mode, trigger_channel, trigger_level))
	{
		qWarning(u8"DAQ控制器配置ADC触发失败");
		return false;
	}

	qInfo(u8"ADC触发配置成功 - 模式: %d, 类型: %d, 通道: %d, 电平: %d",
				static_cast<int>(trigger_type), static_cast<int>(trigger_mode),
				static_cast<int>(trigger_channel), trigger_level);
	return true;
}

bool MainWindow::ConfigADCVoltage()
{
	// 从电压量程下拉框列表获取每个通道的电压量程设置
	std::vector<LockzhinerADCVoltage> voltage_ranges;
	auto legal_voltages = base_device_->GetADCLegalVoltage();

	for (int i = 0; i < voltage_combo_list_.size(); ++i)
	{
		int selected_index = voltage_combo_list_[i]->currentData().toInt();

		if (selected_index < 0 || selected_index >= static_cast<int>(legal_voltages.size()))
		{
			qWarning(u8"通道 %d 电压量程索引超出范围", i + 1);
			return false;
		}

		voltage_ranges.push_back(legal_voltages[selected_index]);
		qInfo(u8"通道 %d 电压量程: %s", i + 1, voltage_combo_list_[i]->currentText().toUtf8().constData());
	}

	if (!base_device_->ConfigADCVoltage(voltage_ranges))
	{
		qWarning(u8"电压量程配置失败");
		return false;
	}

	qInfo(u8"电压量程配置成功");
	return true;
}

bool MainWindow::ConfigACDC()
{
	// 从AC/DC复选框列表获取每个通道的AC/DC设置
	uint8_t ac_dc_mask = 0;

	for (int i = 0; i < ac_dc_checkbox_list_.size(); ++i)
	{
		if (ac_dc_checkbox_list_[i]->isChecked())
		{
			// 复选框选中表示DC模式，设置对应位
			ac_dc_mask |= (1 << i);
		}
		// 复选框未选中表示AC模式，对应位保持0

		QString mode = ac_dc_checkbox_list_[i]->isChecked() ? "DC" : "AC";
		qInfo(u8"通道 %d 模式: %s", i + 1, mode.toUtf8().constData());
	}

	if (!base_device_->ConfigACDC(ac_dc_mask))
	{
		qWarning(u8"AC/DC配置失败");
		return false;
	}

	qInfo(u8"AC/DC配置成功，掩码: 0x%02X", ac_dc_mask);
	return true;
}

void MainWindow::ClickUpdateConfig()
{
	// 采样率配置
	ConfigADCSampleRate();

	// 电压量程配置
	ConfigADCVoltage();

	// 通道使能配置
	ConfigADCChannel();

	// 触发配置
	ConfigADCTrigger();

	// 触发长度配置 (从ui->triggerLengthLineEdit读取)
	bool ok;
	uint32_t trigger_length = ui->triggerLengthLineEdit->text().toUInt(&ok);
	if (!ok || trigger_length == 0)
	{
		qWarning(u8"触发长度格式错误，使用默认值4920");
		trigger_length = 4920;
	}
	if (!base_device_->ConfigADCTriggerLength(trigger_length))
	{
		qWarning(u8"触发长度配置失败");
	}
	else
	{
		qInfo(u8"触发长度配置成功: %u", trigger_length);
	}

	// 超时时间配置 (从ui->triggerTimeoutSpinBox读取)
	uint32_t timeout = static_cast<uint32_t>(ui->triggerTimeoutSpinBox->value());
	if (!base_device_->ConfigTriggerTimeout(timeout))
	{
		qWarning(u8"超时时间配置失败");
	}
	else
	{
		qInfo(u8"超时时间配置成功: %u ms", timeout);
	}

	// AC/DC配置
	ConfigACDC();

	qInfo(u8"下发配置成功");
}

void MainWindow::ClickSoftwareTrigger()
{
	if (connected_count == 0)
	{
		qWarning(u8"请先连接设备");
		return;
	}

	if (!base_device_->ConfigADCTriggerSource(static_cast<uint8_t>(libdaq::device::DAQADCTriggerSource::TriggerSourceSoftware)))
	{
		qWarning(u8"软件触发失败");
		return;
	}
	qInfo(u8"软件触发成功");
}

void MainWindow::ClickStopADCCollection()
{
	if (!base_device_->StopADCCollection())
	{
		qWarning(u8"停止ADC采集失败");
		return;
	}

	is_start_adc_collection_ = false;
	EndOnceCollection();

	qInfo(u8"停止ADC采集成功");
}

void MainWindow::InitWaveWidget()
{
	QVector<QColor> channel_color_ = {
			QColor(0x00, 0x80, 0x00), // 深绿色
			QColor(0xdc, 0x14, 0x3c), // 深红色
			QColor(0x00, 0x8b, 0x8b), // 深青色
			QColor(0xda, 0xa5, 0x20), // 金色
			QColor(0x80, 0x00, 0x80), // 深紫色
			QColor(0x00, 0x00, 0x8b), // 深蓝色
			QColor(0xd2, 0x69, 0x1e), // 深橙色
			QColor(0x48, 0x3d, 0x8b)	// 深紫蓝色
	};
	base_wave_widget_ = QSharedPointer<BaseWaveWidget>::create();
#if defined(USE_DAQ125) || defined(USE_DAQ322)
	base_wave_widget_->InitChannel(8, channel_color_);
#elif defined(USE_DAQ206) || defined(USE_DAQ207)
	base_wave_widget_->InitChannel(2, channel_color_);
#elif defined(USE_DAQ216) || defined(USE_DAQ217)
	base_wave_widget_->InitChannel(4, channel_color_);
#endif
	ui->stackedWidget->addWidget(base_wave_widget_.get());
	ui->stackedWidget->setCurrentWidget(base_wave_widget_.get());
}

void MainWindow::UpdatePlotData(int channel)
{
	if (channel >= adc_data_buffer_.size() || adc_data_buffer_[channel].empty())
	{
		return;
	}

	// 清空该通道数据并重新绘制
	base_wave_widget_->Clear(channel);

	// 添加数据到对应通道
	for (size_t j = 0; j < adc_data_buffer_[channel].size(); ++j)
	{
		base_wave_widget_->AddData(channel, adc_data_buffer_[channel][j]);
	}

	// 更新图表
	UpdateAutoScale();
	base_wave_widget_->replot(QCustomPlot::rpQueuedReplot);

	// 增加已完成线程计数并检查是否所有线程都已完成
	completed_thread_count_++;
	CheckAllThreadsFinished();
}

void MainWindow::UpdateAutoScale()
{
	uint32_t data_length = base_device_->GetCurrentDataLength();
	base_wave_widget_->xAxis->setRange(0, data_length);
}

void MainWindow::CheckAllThreadsFinished()
{
	// 获取启用的通道数量
	QVector<bool> channel_state = GetChannelEnabled();
	int enabled_channel_count = 0;
	for (bool enabled : channel_state)
	{
		if (enabled)
		{
			enabled_channel_count++;
		}
	}

	// 如果所有启用的通道都已完成采集，设置is_start_adc_collection_为false
	if (completed_thread_count_ >= enabled_channel_count && enabled_channel_count > 0)
	{
		is_start_adc_collection_ = false;
		qInfo(u8"所有通道采集完成");
	}
}

void MainWindow::InitSampleRateComboBox()
{
	ui->sampleRateComboBox->clear();

	if (!base_device_)
	{
		return;
	}

	// 获取设备支持的采样率列表
	auto legal_sample_rates = base_device_->GetADCLegalSampleRate();

	for (size_t i = 0; i < legal_sample_rates.size(); ++i)
	{
		auto sample_rate = legal_sample_rates[i];
		QString display_text;

		// 根据采样率枚举值生成显示文本
		int rate_value = static_cast<int>(sample_rate);
		if (rate_value >= 1000000)
		{
			display_text = QString::number(rate_value / 1000000) + "M";
		}
		else if (rate_value >= 1000)
		{
			display_text = QString::number(rate_value / 1000) + "K";
		}
		else
		{
			display_text = QString::number(rate_value);
		}

		// 添加到下拉框，数据部分存储枚举索引
		ui->sampleRateComboBox->addItem(display_text, static_cast<int>(i));
	}

	// 默认选择第一个采样率
	if (ui->sampleRateComboBox->count() > 0)
	{
		ui->sampleRateComboBox->setCurrentIndex(0);
	}
}

void MainWindow::InitChannelConfiguration()
{
	if (!base_device_)
	{
		return;
	}

	// 清空之前的控件列表
	voltage_combo_list_.clear();
	ac_dc_checkbox_list_.clear();

	// 获取设备通道数和支持的电压量程
	int channel_count = base_device_->GetADCLegalChannelSize();
	auto legal_voltages = base_device_->GetADCLegalVoltage();

	// 创建主布局
	QVBoxLayout *main_layout = new QVBoxLayout(ui->channelGroupBox);

	// 为每个通道创建配置行
	for (int i = 0; i < channel_count; ++i)
	{
		// 创建水平布局用于单个通道
		QHBoxLayout *channel_layout = new QHBoxLayout();

		// 通道名称标签
		QLabel *channel_label = new QLabel(QString("通道 %1").arg(i + 1));
		channel_label->setFixedWidth(80);
		channel_label->setStyleSheet("font-weight: bold;");
		channel_layout->addWidget(channel_label);

		// 电压量程下拉框
		QComboBox *voltage_combo = new QComboBox();
		voltage_combo->setObjectName(QString("voltageComboBox_%1").arg(i));

		// 添加电压量程选项
		for (size_t j = 0; j < legal_voltages.size(); ++j)
		{
			auto voltage = legal_voltages[j];
			QString voltage_text;

			// 根据电压枚举值生成显示文本
			switch (voltage)
			{
			case LockzhinerADCVoltage::ADCVoltage_0_1_V:
				voltage_text = "±0.1V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_0_2_V:
				voltage_text = "±0.2V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_0_5_V:
				voltage_text = "±0.5V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_1_V:
				voltage_text = "±1V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_2_V:
				voltage_text = "±2V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_2_5_V:
				voltage_text = "±2.5V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_5_V:
				voltage_text = "±5V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_10_V:
				voltage_text = "±10V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_15_V:
				voltage_text = "±15V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_20_V:
				voltage_text = "±20V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_50_V:
				voltage_text = "±50V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_60_V:
				voltage_text = "±60V";
				break;
			case LockzhinerADCVoltage::ADCVoltage_100_V:
				voltage_text = "±100V";
				break;
			default:
				voltage_text = "未知";
				break;
			}

			// 添加到下拉框，数据部分存储枚举索引
			voltage_combo->addItem(voltage_text, static_cast<int>(j));
		}

		// 默认选择最后一个电压量程（通常是最大量程）
		if (voltage_combo->count() > 0)
		{
			voltage_combo->setCurrentIndex(voltage_combo->count() - 1);
		}

		// 将电压量程下拉框添加到成员变量列表
		voltage_combo_list_.append(voltage_combo);
		channel_layout->addWidget(voltage_combo);

		// AC/DC复选框
		QCheckBox *ac_dc_checkbox = new QCheckBox("DC");
		ac_dc_checkbox->setObjectName(QString("acDcCheckBox_%1").arg(i));
		ac_dc_checkbox->setChecked(true); // 默认为DC模式

		// 将AC/DC复选框添加到成员变量列表
		ac_dc_checkbox_list_.append(ac_dc_checkbox);
		channel_layout->addWidget(ac_dc_checkbox);

		// 添加弹性空间
		channel_layout->addStretch();

		// 将通道布局添加到主布局
		main_layout->addLayout(channel_layout);
	}

	// 添加弹性空间到底部
	main_layout->addStretch();
}

bool MainWindow::IsScrollMode()
{
	// 判断当前触发模式是否为滚动模式（Normal模式）
	if (!base_device_)
	{
		return false;
	}
	
	return base_device_->GetCurrentTriggerType() == LockzhinerADCTriggerType::Normal;
}

void MainWindow::ScrollCollection()
{
	if (!is_start_adc_collection_)
	{
		return;
	}

	// 确保完全清理旧的滚动模式线程
	EndScrollCollection();

	if (!base_device_->StopADCCollection())
	{
		qWarning(u8"停止ADC采集失败");
		is_start_adc_collection_ = false;
		return;
	}

	// 延时50ms，确保设备状态稳定
	QEventLoop loop;
	QTimer::singleShot(50, &loop, SLOT(quit()));
	loop.exec();

	if (!base_device_->StartADCCollection())
	{
		qWarning(u8"启动ADC采集失败");
		is_start_adc_collection_ = false;
		return;
	}

	// 初始化数据缓冲区
	auto channel_count = base_device_->GetADCLegalChannelSize();
	adc_data_buffer_.resize(channel_count);
	for (auto &buffer : adc_data_buffer_)
	{
		buffer.clear();
	}

	// 获取启用的通道
	QVector<bool> channel_state = GetChannelEnabled();

	// 验证通道状态
	bool has_enabled_channel = false;
	for (bool enabled : channel_state)
	{
		if (enabled)
		{
			has_enabled_channel = true;
			break;
		}
	}

	if (!has_enabled_channel)
	{
		qWarning(u8"没有启用的通道，无法开始滚动模式");
		is_start_adc_collection_ = false;
		return;
	}

	// 如果是第一次启动滚动模式，重置数据起始索引
	// 否则保持当前索引，实现数据持续累积
	if (x_start_index_ == 0)
	{
		x_start_index_ = 0;
	}

	// 确保之前的线程已经完全清理
	if (!scroll_mode_adc_thread_.isNull())
	{
		qWarning(u8"滚动模式线程未正确清理，强制重置");
		scroll_mode_adc_thread_.reset();
	}

	// 创建新的滚动模式线程
	try
	{
		scroll_mode_adc_thread_ = QSharedPointer<ScrollModeADCThread>::create(base_device_, channel_state, adc_data_buffer_);
		
		// 连接信号槽
		connect(scroll_mode_adc_thread_.get(), &ScrollModeADCThread::complete, 
				this, &MainWindow::ScrollModeDataReceived, Qt::QueuedConnection);
		
		// 启动线程
		scroll_mode_adc_thread_->start();
		
		qInfo(u8"滚动模式线程创建并启动成功");
	}
	catch (const std::exception& e)
	{
		qWarning(u8"创建滚动模式线程失败: %s", e.what());
		is_start_adc_collection_ = false;
		return;
	}
}

void MainWindow::EndScrollCollection()
{
	if (!scroll_mode_adc_thread_.isNull())
	{
		// 断开所有信号连接，避免重复连接
		disconnect(scroll_mode_adc_thread_.get(), nullptr, this, nullptr);
		
		// 请求线程退出
		scroll_mode_adc_thread_->quit();
		
		// 添加超时机制，避免无限等待
		if (!scroll_mode_adc_thread_->wait(3000)) // 等待3秒
		{
			qWarning(u8"滚动模式线程等待超时，强制终止");
			scroll_mode_adc_thread_->terminate();
			scroll_mode_adc_thread_->wait(1000); // 再等待1秒
		}
		
		// 重置线程指针
		scroll_mode_adc_thread_.reset();
	}
}

void MainWindow::ScrollModeDataReceived(int collection_count)
{
	// 检查采集状态，如果已停止则不处理数据
	if (!is_start_adc_collection_)
	{
		return;
	}

	// 滚动模式数据接收槽函数
	if (collection_count == 0)
	{
		// 第一次采集数据可能为空，跳过
		return;
	}

	// 更新滚动模式数据到波形控件（包含X轴范围调整）
	UpdateScrollModeData();
}

void MainWindow::UpdateScrollModeData()
{
	// 检查采集状态和基本组件
	if (!is_start_adc_collection_ || !base_wave_widget_ || !base_device_)
	{
		return;
	}

	// 获取启用的通道
	QVector<bool> channel_state = GetChannelEnabled();

	// 计算最大数据长度
	uint32_t max_data_length = 0;
	for (uint32_t i = 0; i < adc_data_buffer_.size(); ++i)
	{
		if (adc_data_buffer_[i].size() > max_data_length)
		{
			max_data_length = adc_data_buffer_[i].size();
		}
	}

	// 为每个启用的通道添加新数据（不清空已有数据）
	for (uint32_t i = 0; i < adc_data_buffer_.size(); ++i)
	{
		if (i < channel_state.size() && channel_state[i] && !adc_data_buffer_[i].empty())
		{
			// 添加新数据到对应通道
			for (uint32_t j = 0; j < adc_data_buffer_[i].size(); ++j)
			{
				double x_value = x_start_index_ + j;
				base_wave_widget_->AddData(i, x_value, adc_data_buffer_[i][j]);
			}
		}
	}

	// 更新数据起始索引
	x_start_index_ += max_data_length;

	// 动态计算滚动窗口大小
	uint32_t device_data_length = base_device_->GetCurrentDataLength();
	
	// X轴始终跟随最新数据滚动
	if (x_start_index_ > device_data_length)
	{
		// 当数据超过窗口大小时，显示最新的数据窗口
		base_wave_widget_->xAxis->setRange(x_start_index_ - device_data_length, x_start_index_);
	}
	else
	{
		// 数据还不够多时，从0开始显示到当前位置
		base_wave_widget_->xAxis->setRange(0, x_start_index_);
	}

	// 自动调整Y轴范围以适应当前显示的数据
	base_wave_widget_->AutoScale_Y();

	// 重新绘制波形
	base_wave_widget_->replot(QCustomPlot::rpQueuedReplot);
}
